import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import './SearchPage.css';
import VideoCard from './VideoCard';
import LiveCard from './LiveCard';
import { useFollow } from '../../context/FollowContext.jsx';

// Use same data from DiscoverPage
// Video list data
const videoList = [
  {
    id: 1,
    avatar: '/6.jpg',
    username: '张三',
    likes: '7.9万',
    img: '/6.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['美食', '推荐']
  },
  {
    id: 2,
    avatar: '/7.jpg',
    username: '李四',
    likes: '7.9万',
    img: '/7.jpg',
    video: '/meinv.mp4',
    isFollow: true,
    category: ['游戏', '推荐']
  },
  {
    id: 3,
    avatar: '/9.jpg',
    username: '王五',
    likes: '7.9万',
    img: '/10.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['音乐', '推荐']
  },
  {
    id: 4,
    avatar: '/11.jpg',
    username: '赵六',
    likes: '7.9万',
    img: '/11.jpg',
    video: '/meinv.mp4',
    isFollow: true,
    category: ['舞蹈', '推荐']
  },
  {
    id: 5,
    avatar: '/12.jpg',
    username: '孙七',
    likes: '7.9万',
    img: '/12.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['美食', '附近']
  },
];

// Live list data
const liveList = [
  {
    id: 101,
    cover: '/10.jpg',
    title: '天津 摇滚不死',
    location: '天津',
    viewer: 420,
    category: ['音乐', '推荐']
  },
  {
    id: 102,
    cover: '/11.jpg',
    title: '北京 街头艺人',
    location: '北京',
    viewer: 666,
    category: ['音乐', '推荐']
  },
  {
    id: 103,
    cover: '/12.jpg',
    title: '上海 时尚穿搭分享',
    location: '上海',
    viewer: 823,
    category: ['时尚', '推荐']
  },
];

// User list data
const userList = [
  {
    id: 1001,
    avatar: '/6.jpg',
    username: '张三',
    description: '美食博主',
    followers: '12.5万',
    isFollow: false
  },
  {
    id: 1002,
    avatar: '/7.jpg',
    username: '李四',
    description: '游戏主播',
    followers: '45.8万',
    isFollow: true
  },
  {
    id: 1003,
    avatar: '/9.jpg',
    username: '王五',
    description: '音乐制作人',
    followers: '8.3万',
    isFollow: false
  },
];

// Hot search keywords
const hotKeywords = ['美食探店', '游戏实况', '街头时尚', '健身教程', '旅行vlog'];

const SearchPage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { isFollowing, followUser, unfollowUser } = useFollow();
  const [searchQuery, setSearchQuery] = useState('');
  const [searchHistory, setSearchHistory] = useState([]);
  const [activeTab, setActiveTab] = useState('综合');
  const [searchResults, setSearchResults] = useState({
    videos: [],
    lives: [],
    users: []
  });
  const [showResults, setShowResults] = useState(false);
  
  // Tabs for filtering results
  const tabs = ['综合', '视频', '用户', '直播'];
  
  // Load search history from localStorage on component mount
  useEffect(() => {
    const storedHistory = localStorage.getItem('searchHistory');
    if (storedHistory) {
      setSearchHistory(JSON.parse(storedHistory));
    }
    
    // Check if there's a query parameter in the URL
    const urlParams = new URLSearchParams(location.search);
    const queryParam = urlParams.get('query');
    if (queryParam) {
      setSearchQuery(queryParam);
      handleSearch(queryParam);
    }
  }, [location]);
  
  // Handle search submission
  const handleSearch = (query = searchQuery) => {
    if (!query.trim()) return;
    
    // Save to search history
    const newHistory = [query, ...searchHistory.filter(item => item !== query)].slice(0, 10);
    setSearchHistory(newHistory);
    localStorage.setItem('searchHistory', JSON.stringify(newHistory));
    
    // Filter videos
    const filteredVideos = videoList.filter(video => 
      video.username.includes(query) || 
      video.category.some(cat => cat.includes(query))
    ).map(video => ({
      ...video,
      isFollow: isFollowing(video.id) // 使用全局关注状态覆盖本地状态
    }));
    
    // Filter lives
    const filteredLives = liveList.filter(live => 
      live.title.includes(query) || 
      live.location.includes(query) ||
      live.category.some(cat => cat.includes(query))
    );
    
    // Filter users
    const filteredUsers = userList.filter(user => 
      user.username.includes(query) || 
      user.description.includes(query)
    ).map(user => ({
      ...user,
      isFollow: isFollowing(user.id) // 使用全局关注状态覆盖本地状态
    }));
    
    // Update results
    setSearchResults({
      videos: filteredVideos,
      lives: filteredLives,
      users: filteredUsers
    });
    
    setShowResults(true);
    
    // Update URL without reloading the page
    navigate(`/search?query=${encodeURIComponent(query)}`, { replace: true });
  };
  
  // Clear search history
  const clearHistory = () => {
    setSearchHistory([]);
    localStorage.removeItem('searchHistory');
  };
  
  // Handle keyword click
  const handleKeywordClick = (keyword) => {
    setSearchQuery(keyword);
    handleSearch(keyword);
  };
  
  // Go to video detail
  const goToVideo = (id) => {
    navigate(`/video/${id}`);
  };
  
  // Go to live room
  const goToLive = (id) => {
    navigate(`/live/${id}`);
  };
  
  // Go to user profile
  const goToUserProfile = (id) => {
    // Assuming you have a user profile page
    navigate(`/user/${id}`);
  };
  
  // Go back to previous page
  const goBack = () => {
    navigate(-1);
  };
  
  // Go to homepage
  const goToHomepage = () => {
    navigate('/homepage');
  };
  
  // Filter results based on active tab
  const getFilteredResults = () => {
    switch (activeTab) {
      case '视频':
        return { videos: searchResults.videos, lives: [], users: [] };
      case '用户':
        return { videos: [], lives: [], users: searchResults.users };
      case '直播':
        return { videos: [], lives: searchResults.lives, users: [] };
      default:
        return searchResults;
    }
  };
  
  // Check if we have any results
  const hasResults = () => {
    const { videos, lives, users } = getFilteredResults();
    return videos.length > 0 || lives.length > 0 || users.length > 0;
  };
  
  return (
    <div className="search-page">
      {/* Search header */}
      <div className="search-header">
        <div className="back-button" onClick={goBack}>
          ←
        </div>
        <div className="home-button" onClick={goToHomepage}>
          首页
        </div>
        <div className="search-input-container">
          <input
            type="text"
            className="search-input"
            placeholder="搜索视频、用户、话题"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
          />
          {searchQuery && (
            <span className="clear-input" onClick={() => setSearchQuery('')}>
              ×
            </span>
          )}
        </div>
        <div className="search-button" onClick={() => handleSearch()}>
          搜索
        </div>
      </div>
      
      {/* Search content */}
      <div className="search-content">
        {!showResults ? (
          <>
            {/* Hot search section */}
            <div className="search-section">
              <div className="section-header">
                <h3>热门搜索</h3>
              </div>
              <div className="keyword-list">
                {hotKeywords.map((keyword, index) => (
                  <div
                    key={index}
                    className="keyword-item"
                    onClick={() => handleKeywordClick(keyword)}
                  >
                    {index < 3 && <span className="hot-label">热</span>}
                    {keyword}
                  </div>
                ))}
              </div>
            </div>
            
            {/* Search history section */}
            {searchHistory.length > 0 && (
              <div className="search-section">
                <div className="section-header">
                  <h3>搜索历史</h3>
                  <span className="clear-history" onClick={clearHistory}>
                    清除
                  </span>
                </div>
                <div className="history-list">
                  {searchHistory.map((item, index) => (
                    <div
                      key={index}
                      className="history-item"
                      onClick={() => handleKeywordClick(item)}
                    >
                      <span className="history-icon">⏱</span>
                      {item}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </>
        ) : (
          <>
            {/* Tabs for filtering results */}
            <div className="search-tabs">
              {tabs.map((tab) => (
                <div
                  key={tab}
                  className={`tab ${activeTab === tab ? 'active' : ''}`}
                  onClick={() => setActiveTab(tab)}
                >
                  {tab}
                  {activeTab === tab && <div className="tab-indicator"></div>}
                </div>
              ))}
            </div>
            
            {/* Results display */}
            {hasResults() ? (
              <div className="search-results">
                {/* User results */}
                {getFilteredResults().users.length > 0 && (
                  <div className="result-section">
                    <h3>用户</h3>
                    <div className="user-results">
                      {getFilteredResults().users.map((user) => (
                        <div
                          key={user.id}
                          className="user-result-item"
                          onClick={() => goToUserProfile(user.id)}
                        >
                          <img src={user.avatar} alt={user.username} className="user-avatar" />
                          <div className="user-info">
                            <div className="user-name">{user.username}</div>
                            <div className="user-desc">{user.description}</div>
                            <div className="user-followers">{user.followers}粉丝</div>
                          </div>
                          <button 
                            className={`follow-btn ${user.isFollow ? 'following' : ''}`}
                            onClick={(e) => {
                              e.stopPropagation();
                              if (user.isFollow) {
                                unfollowUser(user.id);
                              } else {
                                followUser(user.id, user.username);
                              }
                            }}
                          >
                            {user.isFollow ? '已关注' : '关注'}
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                
                {/* Live results */}
                {getFilteredResults().lives.length > 0 && (
                  <div className="result-section">
                    <h3>直播</h3>
                    <div className="live-results">
                      {getFilteredResults().lives.map((live) => (
                        <div 
                          key={live.id} 
                          className="live-result-item"
                          onClick={() => goToLive(live.id)}
                        >
                          <LiveCard live={live} />
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                
                {/* Video results */}
                {getFilteredResults().videos.length > 0 && (
                  <div className="result-section">
                    <h3>视频</h3>
                    <div className="video-results">
                      {getFilteredResults().videos.map((video) => (
                        <div 
                          key={video.id} 
                          className="video-result-item"
                          onClick={() => goToVideo(video.id)}
                        >
                          <VideoCard video={video} />
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            ) : (
              <div className="no-results">
                <div className="no-results-icon">🔍</div>
                <div className="no-results-text">未找到与"{searchQuery}"相关的内容</div>
                <div className="no-results-tips">
                  请尝试其他关键词，或检查输入是否有误
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default SearchPage; 